package top.lyc829.aircontroller.ui.login

import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import top.lyc829.aircontroller.MyApp
import top.lyc829.aircontroller.logic.network.AllResponse
import top.lyc829.aircontroller.logic.network.HttpUtil
import java.io.IOException

class LoginViewModel: ViewModel() {

    val auth: LiveData<String>
    get() = _auth

    private val _auth = MutableLiveData<String>()

    fun doLogin(username: String, password: String) {
        val map = mutableMapOf("username" to username, "password" to password)
        HttpUtil.postHttp("/login", map, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Looper.prepare()
                //Log.d("MyTag", e.toString())
                Toast.makeText(MyApp.context, "网络开小差了...", Toast.LENGTH_LONG).show()
                Looper.loop()

            }

            override fun onResponse(call: Call, response: Response) {

                if (response.body?.let { parseJsonWithGSON(it.string()).code } == "200") {
                    // 设置auth
                    _auth.postValue(response.header("auth").toString())
                }

            }
        })
    }

    fun parseJsonWithGSON(jsonStr: String): AllResponse {
        val gson = Gson()
        return gson.fromJson(jsonStr, AllResponse::class.java)
    }
}